import Vue from 'vue'
import VueI18n from 'vue-i18n'
import i18nData from '@/assets/i18n.json' //i18n数据定义

Vue.use(VueI18n)

/* 第一次访问没有值，给个默认值，LanguageSwitch中会设置localStorage.locale 
let locale = localStorage.locale
if(!locale) {
  locale =	navigator.language||navigator.userLanguage
  locale = locale.replace('-', '_') //zh-CN --> zh_CN
  if (!locale.includes('_')) {
    if (locale == 'zh') {
      locale = 'zh_CN'
    } else {
      locale = 'en_US'
    }
  }
  
  localStorage.locale = locale
}
*/

// 固定设置成中文语言
localStorage.locale = 'zh_CN'

let convertI18n = function(i18n){
  let localeArr = [];
  localeArr.push('zh_CN')
  localeArr.push('en_US')

  let result = {};
  for (let i=0;i<localeArr.length;i++) {
    let locale = localeArr[i]
    let localeItem = getLocaleItem(i18n, locale)
    result[locale] = localeItem;
  }

  return result
}

let getLocaleItem = function(i18n, locale){
  let result = {}
  for (let key in i18n) {
    let messageMap = i18n[key]
    let localeValue = messageMap[locale]
    result[key] = localeValue
  }

  return result
}

// 准备翻译的语言环境信息
const messages = convertI18n(i18nData)

// 通过选项创建 VueI18n 实例
const i18n = new VueI18n({
  locale: localStorage.locale, // 设置地区
  messages, // 设置地区信息
})

export default i18n